<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\api\controller\v1;

use app\api\model\UserWeixin as UserWeixinModel;
use app\api\service\Token;
use app\lib\exception\UserException;
use think\Config;
use think\Request;
use WeMini\Crypt;

/**
 * 用户微信表
 * Class UserWeixin
 * @package app\api\controller\v1
 */
class UserWeixin extends BaseController
{
    /**
     * @Desc 获取用户数据
     * @return int[]
     */
    public function getUser()
    {
        return UserWeixinModel::getUser();
    }

    /**
     * @Desc 更新用户数据
     * @return int[]
     */
    public function updateUser()
    {
        $userInfo = Request::instance()->put();
        return UserWeixinModel::updateUser($userInfo);
    }

    /**
     * @Desc 解密消息, 获取用户手机号
     * @return bool
     */
    public function getUserPhone()
    {
        $param = Request::instance()->post();
        $sessionKey = Token::getSessionKeyFromCache();
        // 小程序配置
        $config = [
            'appid'     => Config::get('wechat.appid'),
            'appsecret' => Config::get('wechat.appsecret'),
        ];
        // 实例SDK
        $mini = new Crypt($config);
        // 数据解码
        $data = $mini->decode($param['iv'], $sessionKey, $param['encryptedData']);
        if (!$data) {
            throw new UserException([
                'code'      => 400,
                'message'   => '获取手机号失败',
                'errorCode' => 30001,
            ]);
        }
        return $data;
    }
}